package top.oauth2.sms.service.impl;

import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.oauth2.sms.component.SmsProperties;
import top.oauth2.sms.enums.SmsLengthEnum;
import top.oauth2.sms.enums.SmsResponseCodeEnum;
import top.oauth2.sms.exception.BaseException;
import top.oauth2.sms.service.SmsService;
import top.oauth2.sms.utils.SmsCodeUtil;
import top.oauth2.sms.utils.SmsUtil;

/**
 * 腾讯短信服务实现类
 * @author xphu
 * @version 1.0
 * @date 2021/9/16 11:55
 */
@Service("penguinSmsService")
public class PenguinSmsServiceImpl implements SmsService {

    @Autowired
    private SmsProperties smsProperties;

    /**
     * 发送短信验证码
     *
     * @param phone      手机号
     * @param codeLength 短信code长度
     * @param templateId 短信模板id
     * @author xphu
     * @date: 2021/9/16 10:11
     */
    @Override
    public boolean sendSmsCode(String phone, Integer codeLength, String templateId) throws BaseException {
        String code = SmsCodeUtil.createSmsRandomCode(SmsLengthEnum.getSmsLengthEnum(codeLength));
        return sendSmsCode(phone, code, templateId);
    }

    /**
     * 验证短信验证码
     *
     * @param phone      手机号
     * @param code       验证码
     * @param templateId 模板名称
     * @author xphu
     * @date: 2021/9/16 10:11
     */
    @Override
    public boolean sendSmsCode(String phone, String code, String templateId) throws BaseException {
        if (StringUtils.isEmpty(code)){
            code = SmsCodeUtil.createSmsRandomCode(SmsLengthEnum.SMS_LENGTH_6);
        }
        SendStatus[] statuses = SmsUtil.sendSms(smsProperties, templateId, new String[]{code}, new String[]{phone});
        if (statuses != null && statuses.length > 0){
            SendStatus status = statuses[0];
            return status.getCode().equals(SmsResponseCodeEnum.OK.getCode());
        }
        return false;
    }
}
